package org.example.controller;

import org.example.dto.ApiResponse;
import org.example.service.AccessStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 访问统计控制器
 * 提供点击量统计相关的API接口
 */
@RestController
@RequestMapping("/api/statistics")
public class StatisticsController {
    
    @Autowired
    private AccessStatisticsService accessStatisticsService;
    
    /**
     * 获取短链接的访问统计概览
     */
    @GetMapping("/overview/{shortCode}")
    public ApiResponse<String> getStatisticsOverview(@PathVariable String shortCode) {
        try {
            String overview = accessStatisticsService.getAccessStatisticsOverview(shortCode);
            return ApiResponse.success(overview);
        } catch (Exception e) {
            return ApiResponse.error("获取统计概览失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取短链接的总访问量
     */
    @GetMapping("/total/{shortCode}")
    public ApiResponse<Map<String, Object>> getTotalAccessCount(@PathVariable String shortCode) {
        try {
            int totalCount = accessStatisticsService.getTotalAccessCount(shortCode);
            
            Map<String, Object> result = new HashMap<>();
            result.put("shortCode", shortCode);
            result.put("totalAccessCount", totalCount);
            result.put("timestamp", LocalDateTime.now());
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("获取总访问量失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取短链接的日访问量
     */
    @GetMapping("/daily/{shortCode}")
    public ApiResponse<Map<String, Object>> getDailyAccessCount(
            @PathVariable String shortCode,
            @RequestParam(defaultValue = "") String date) {
        try {
            // 如果没有指定日期，使用今天
            if (date.isEmpty()) {
                date = LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            }
            
            int dailyCount = accessStatisticsService.getDailyAccessCount(shortCode, date);
            long uniqueIpCount = accessStatisticsService.getUniqueIpCount(shortCode, date);
            
            Map<String, Object> result = new HashMap<>();
            result.put("shortCode", shortCode);
            result.put("date", date);
            result.put("dailyAccessCount", dailyCount);
            result.put("uniqueIpCount", uniqueIpCount);
            result.put("timestamp", LocalDateTime.now());
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("获取日访问量失败: " + e.getMessage());
        }
    }
}
